<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" :is-search-disabled="isSearchDisabled" @reset="resetPage">
      <el-col :span="8" :xs="24" v-show="$permiss[210]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select
              style="width: 100%"
              v-model="page.adminUserId"
              @change="tenantChange"
              clearable
          >
            <el-option
                v-for="item in tenantList"
                :key="item.adminUserId"
                :label="item.adminName"
                :value="item.adminUserId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')">
          <el-input v-model="page.idcard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('交易流水')" prop="transferNumber">
          <el-input v-model="page.transferNumber"></el-input>
        </el-form-item>
      </el-col>

      <!--      <el-col :span="8" :xs="24" v-show="$permiss[212]">-->
      <!--        <el-form-item :label="$t('订单状态')" prop="approvalResult">-->
      <!--          <el-select style="width: 100%" v-model="page.approvalResult">-->
      <!--            <el-option-->
      <!--                v-for="item in orderStatus"-->
      <!--                :key="item.value"-->
      <!--                :label="item.label"-->
      <!--                :value="item.value"-->
      <!--            ></el-option>-->
      <!--          </el-select>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->

      <el-col :span="8" :xs="24" v-show="$permiss[211]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select
              style="width: 100%"
              v-model="page.productName"
              clearable
          >
            <el-option
                v-for="item in productList"
                :key="item.productId"
                :label="item.appName"
                :value="item.productName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('还款类型')" prop="transferType">
          <el-select
              style="width: 100%"
              v-model="page.transferType"
              clearable
          >
            <el-option :label="$t('线下')" :value="1"></el-option>
            <el-option :label="$t('线上')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('还款状态')">
          <el-select
              style="width: 100%"
              v-model="page.refundState"
              clearable
          >
            <el-option :label="$t('还款成功')" :value="21"></el-option>
            <el-option :label="$t('还款退回')" :value="12"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[805]">
        <el-form-item :label="$t('还款渠道')" prop="channelCode">
          <el-select
              style="width: 100%"
              v-model="page.channelCode"
              clearable
          >
            <el-option
                v-for="item in channelList"
                :key="item"
                :label="item"
                :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('回款时间')" prop="repaymentTime">
          <el-date-picker
              v-model="page.repaymentTime"
              style="width: 100%"
              type="daterange"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="~"
              unlink-panels
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>


    <el-card shadow="never" style="margin-top: 10px">
      <el-row :gutter="24" style="margin: 0 0 10px 0;line-height: 32px;" v-show="$permiss[213]">
        <el-col :span="12">
          <el-link type="primary" :underline="false">
            <span style="font-size: 18px">
              {{ $t("回款总金额") }} : {{ totalAmount }}
            </span>
          </el-link>
        </el-col>
        <el-col :span="12" style="text-align: right" v-show="$permiss[738]">
          <el-button
              type="primary"
              @click="exportsExcel"
              :loading="exportsLoading"
          >{{ $t("导出") }}
          </el-button>
        </el-col>
      </el-row>
      <Table
          :loading="loading"
          :page="page"
          :table-column="tableColumn"
          :table-data="tableData"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
      >
        <template slot="refundState" slot-scope="{row}">
          {{row.refundState === 21 ? $t('还款成功') : $t('还款退回')}}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button v-show="$permiss[1594] && row.refundState === 21"  @click="refundBack(row)" type="text">{{ $t('还款退回') }}</el-button>
        </template>
      </Table>
    </el-card>
  </div>
</template>

<script>

import {export_json_to_excel} from "@/utils/exportExcel";
import {dateFormatSection, defaultTimeDate} from '@/utils/tools'
import {selectProduct, selectTenant} from "@/api/system";
import {refundBillsList, refundBillsExport, refundBillsSucceed, refundBack} from "@/api/finance";

export default {
  name: "collectionDetails",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        repaymentTime: defaultTimeDate(14),
        rollOverTime: null,
      },
      tableData: [],
      tableColumn: [
        {
          label: this.$t("订单编号"),
          prop: "loanRecordId",
          fixed: "left",
          align: "center",
          width: 150,
        },
        {label: this.$t("用户姓名"), prop: "name", align: "center"},
        {label: this.$t("手机号码"), prop: "phone", align: "center"},
        {label: this.$t("身份证"), prop: "idCard", align: "center", width: 100,},
        {
          label: this.$t("到账时间"),
          prop: "actualRefundTimestamp",
          align: "center",
          width: 200,
        },
        {
          label: this.$t("还款金额"),
          prop: "actualRefundAmount",
          align: "center",
        },
        {label: this.$t("还款类型"), prop: "transferType", align: "center"},
        {label: this.$t("还款渠道"), prop: "channelCode", align: "center"},
        {
          label: this.$t("交易流水"),
          prop: "transferNumber",
          align: "center",
          width: 200,
        },
        // {label: this.$t('回款银行'), prop: 'receiverBank', align: 'center',},
        {label: this.$t("操作人"), prop: "inputUserId", align: "center"},
        {
          label: this.$t("操作时间"),
          prop: "inputTimestamp",
          align: "center",
          width: 200,
        },
        {label: this.$t("还款状态"), prop: "refundState", align: "center",slot:'refundState'},
        {label: this.$t("APP名称"), prop: "appName", align: "center"},
        {
          label: this.$t("所属租户"),
          prop: "adminUserName",
          align: "center",
          isHide: !this.$permiss[210],
        },
        {
          label: this.$t("操作"),
          slot: "handle",
          align: "center",
          isHide: !this.$permiss[1594],
          fixed:'right',
        },
      ],
      orderStatus: [
        {label: this.$t("全部"), value: 0},
        {label: this.$t("待还款"), value: 1},
        {label: this.$t("结清"), value: 2},
      ],
      loading: false,
      tenantList: [],
      productList: [],
      totalAmount: 0,
      exportsLoading: false,
      isSearchDisabled: false
    };
  },
  computed: {
    channelList() {
      return process.env.VUE_APP_REGION === 'moxige' ? ["PANDAPAY", "MXFLINPAY", "STP",] : ['BAOKIM', 'FUNPAY']
    }
  },
  mounted() {
    this.getTableData();
    this.getSelectList();
  },
  methods: {
    async getTableData() {
      this.loading = true;
      this.isSearchDisabled = true
      const repaymentTime = dateFormatSection(this.page.repaymentTime)
      const params = Object.assign({}, this.page, {
        datetimeStart: repaymentTime && repaymentTime.length > 1 ? repaymentTime[0] : undefined,
        datetimeEnd: repaymentTime && repaymentTime.length > 1 ? repaymentTime[1] : undefined,
      });
      // 删除日期属性
      delete params.repaymentTime;
      this.getAmount(params);
      const res = await refundBillsList(params);
      if (res.code === 1) {
        const {list, total} = res.data;
        this.tableData = list.map((item) => {
          item.avoidAudit = item.avoidAudit === 1 ? this.$t("是") : this.$t("否");
          item.transferType = item.transferType === 1 ? this.$t("线下") : this.$t("线上");
          return item;
        });
        this.page = Object.assign({}, this.page, {
          total: total,
        });
        this.isSearchDisabled = false
        this.loading = false;
      } else {
        this.isSearchDisabled = true
        this.loading = false;
      }
    },
    async getAmount(params) {
      const res = await refundBillsSucceed(params);
      if (res.code === 1) {
        this.totalAmount = res.data;
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData();
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', null)
      })
    },
    async getSelectList() {
      selectProduct().then(res => {
        this.productList = res.data
      })
      selectTenant().then(res => {
        this.tenantList = res.data
      })
    },
    // 还款退回
    refundBack(row) {
      this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
        type: "warning",
      }).then(async () => {
        const formData = new FormData()
        formData.append('id', row.id)
        const res = await refundBack(formData)
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.repaymentTime || [])
      const params = {
        ...this.page,
        datetimeStart,
        datetimeEnd,
      };
      delete params.repaymentTime;
      const res = await refundBillsExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.avoidAudit = item.avoidAudit === 1 ? this.$t("是") : this.$t("否");
          item.transferType = item.transferType === 1 ? this.$t("线下") : this.$t("线上");
          return item;
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("回款明细表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
    resetPage() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      };
      this.getTableData();
    },
  },
};
</script>

<style scoped>
</style>
